/**
 * Copyright (c) 2006 RiseSoft Co.,Ltd  
 * $Header$
 */
package net.risesoft.risebi.collection.web.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;

import net.risesoft.risebi.collection.groovy.Fault;
import net.risesoft.risebi.collection.model.Application;
import net.risesoft.risebi.collection.model.Formula;
import net.risesoft.risebi.collection.model.RangeObj;
import net.risesoft.risebi.collection.model.ReportData;
import net.risesoft.risebi.collection.model.ReportInstance;
import net.risesoft.risebi.collection.model.ReportInstanceR6;
import net.risesoft.risebi.collection.model.Template;
import net.risesoft.risebi.collection.model.TemplateIndication;
import net.risesoft.risebi.collection.model.User;
import net.risesoft.risebi.collection.service.DataOperationManager;
import net.risesoft.risebi.collection.service.DataOperationManagerR6;
import net.risesoft.risebi.collection.service.ReportInstanceManager;
import net.risesoft.risebi.collection.service.ReportInstanceManagerR6;
import net.risesoft.risebi.collection.service.TemplateManager;
import net.risesoft.risebi.collection.web.BaseDataOperationAction;
import net.risesoft.risebi.commons.util.ExceptionUtil;
import net.risesoft.risebi.commons.util.JSONUtil;
import net.sf.json.JSONObject;

/**
 * 
 * @author <a href="mailto: chenjian@risesoft.net">陈健</a>
 * @version $Revision$
 * 
 */
@Namespace("/client/DataOperationAction")
public class DataOperationAction extends BaseDataOperationAction {

	private static final long serialVersionUID = 7933537408403814382L;
	
	private String reportTaskID;

	private ReportInstanceManagerR6 reportInstanceManagerR6;
	
	private DataOperationManagerR6 dataOperationManagerR6;
	
	private TemplateManager templateManager;

	
	public TemplateManager getTemplateManager() {
		return templateManager;
	}

	public void setTemplateManager(TemplateManager templateManager) {
		this.templateManager = templateManager;
	}

	public ReportInstanceManagerR6 getReportInstanceManagerR6() {
		return reportInstanceManagerR6;
	}

	public void setReportInstanceManagerR6(
			ReportInstanceManagerR6 reportInstanceManagerR6) {
		this.reportInstanceManagerR6 = reportInstanceManagerR6;
	}

	public DataOperationManagerR6 getDataOperationManagerR6() {
		return dataOperationManagerR6;
	}

	public void setDataOperationManagerR6(
			DataOperationManagerR6 dataOperationManagerR6) {
		this.dataOperationManagerR6 = dataOperationManagerR6;
	}

	@Action(value = "prepareAdd", results = { @Result(name = "success", location = "/client/datapage/dataAdd.jsp"), @Result(name = "prepareEdit", location = "/client/datapage/dataEdit.jsp") })
    public String prepareAdd() throws Exception {
        method = "add";
        this.setType("1"); // 1表示普通报表，2表示基本情况表

        //User user = this.getSessionUser();
  
        this.setRi(this.getReportInstanceManagerR6().getR6Object(reportTaskID, this.getRi().getGuid()));
        this.setTemplateGuid(this.getRi().getTemplate().getGuid());
        this.setSelectedTask(this.getRi().getApplication());
        //service = ri.getService();
        //selectedTask = ri.getApplication();

        if (this.getRd() == null) {
            this.setRd(new ReportData());
            Map<String, String> indis = new HashMap<String, String>();
            Map<String, RangeObj> ranges = new HashMap<String, RangeObj>();
            this.getRd().setRanges(ranges);
            this.getRd().setIndis(indis);
        }

        // 假如已经填报或者有审核错误，就转到 prepareEdit
        if (this.getRi().getStatus() != null && this.getRi().getStatus() != ReportInstance.STATUS_NO) {
            method = "edit";
            //calculator.doCalculate(templateGuid, rd, Formula.EXECUTEPOINT_EDIT, user, ri);
            return PREPAREEDIT;
        }

        //calculator.doCalculate(templateGuid, rd, Formula.EXECUTEPOINT_ADD, user, ri);
        return SUCCESS;
    }

    @Action(value = "prepareEdit", results = { @Result(name = "success", location = "/client/datapage/dataEdit.jsp"), @Result(name = "prepareAdd", location = "/client/datapage/dataAdd.jsp") })
    public String prepareEdit() throws Exception {
        method = "edit";
        this.setType("1"); // 1表示普通报表，2表示基本情况表
        
        //User user = this.getSessionUser();

        this.setRi(this.getReportInstanceManagerR6().getR6Object(reportTaskID, this.getRi().getGuid()));
        this.setTemplateGuid(this.getRi().getTemplate().getGuid());
        this.setSelectedTask(this.getRi().getApplication());
        //if (this.getRi().getLockStatus() == 1) {
        //    throw new Exception("该报表已经被锁定，不能再被填报");
        //}

        //service = ri.getService();
        //selectedTask = ri.getApplication();

        this.setRd(this.getDataOperationManagerR6().getR6ReportData(reportTaskID,this.getRi(), this.getTemplateGuid()));

        // 假如填报状态为null或者为0，就转到 prepareAdd
        if (this.getRi().getStatus() == null || this.getRi().getStatus() == ReportInstance.STATUS_NO) {
            method = "add";
            return PREPAREADD;
        }


        return SUCCESS;
    }
    
    @Action(value = "refreshJson")
    public String refreshJson()
            throws Exception
        {
            try
            {
                List newList = new ArrayList();
                if("jsonToolTipList".equalsIgnoreCase(whichJson))
                {
                    //ri = (ReportInstance)reportInstanceManager.getObject(ReportInstance.class, ri.getGuid());
                    this.setRi(this.getReportInstanceManagerR6().getR6Object(reportTaskID, this.getRi().getGuid()));
                    //Template template = ri.getTemplate();
                    Template template = (Template)this.getTemplateManager().getObject(Template.class, this.getRi().getTemplateGuid());
                    List list1 = template.getTemplateIndications();
                    for(Iterator iterator = list1.iterator(); iterator.hasNext();)
                    {
                        TemplateIndication ti = (TemplateIndication)iterator.next();
                        String tooltip = ti.getTooltip();
                        if(StringUtils.isNotBlank(tooltip))
                        {
                            HashMap map = new HashMap();
                            map.put("tooltip", tooltip);
                            String range_Name = ti.getRange_Name();
                            if(StringUtils.isBlank(range_Name))
                                map.put("cell", (new StringBuilder("rd.indis['")).append(ti.getAlias_Name()).append("']").toString());
                            else
                                map.put("cell", (new StringBuilder("rd.ranges['")).append(range_Name).append("'].cols['").append(ti.getAlias_ColumnCode()).append("']").toString());
                            newList.add(map);
                        }
                    }

                    json = JSONUtil.getJsonString(null, null, newList, new String[0]);
                }
            }
            catch(Exception e)
            {
                json = "[]";
                e.printStackTrace();
            }
            return "ajax";
        }
    
    @Action(value = "saveData")
    public String saveData() throws Exception {
        Map map = new HashMap();

        try {
            User user = this.getSessionUser();
            //ri = (ReportInstance) reportInstanceManager.getObject(ReportInstance.class, ri.getGuid());
            this.setRi(this.getReportInstanceManagerR6().getR6Object(reportTaskID, this.getRi().getGuid()));
            Map returnedMap = this.getDataOperationManagerR6().addR6ReportData(reportTaskID,this.getClientJsValidationError(),this.getRi(),this.getRd(), this.getTemplateGuid(), user);
            List<Fault> containedFaults = (List<Fault>) returnedMap.get("containedFaults");
            this.setContainedFaults(containedFaults);
            if (this.getContainedFaults() == null || this.getContainedFaults().isEmpty()) {
                map.put("success", true);
                map.put("reason", "保存成功！");
                map.put("containedFaults", "[]");
            } else {
                map.put("success", false);
                map.put("reason", "保存成功，但出现校验或审核错误！");
                map.put("containedFaults", this.getContainedFaults());
            }
        } catch (Exception e) {
            //log.error(ExceptionUtil.transformException(e));
        	e.printStackTrace();
            map.put("success", false);
            map.put("reason", "保存时程序出现异常！\r" + e.getMessage());
            map.put("containedFaults", "[]");
        }

        this.json = JSONObject.fromObject(map).toString();
        return AJAX;
    }

	public String getReportTaskID() {
		return reportTaskID;
	}

	public void setReportTaskID(String reportTaskID) {
		this.reportTaskID = reportTaskID;
	}

}
